package cn.xuchunh.campusbbs.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Calendar;
import java.util.List;

import cn.xuchunh.campusbbs.AppContext;
import cn.xuchunh.campusbbs.R;
import cn.xuchunh.campusbbs.ui.activities.WelcomeActivity;

/**
 * Created by XuChunH on 2015/8/31.
 */
public class AppUtil {

    public static String getHash() {
        String s = String.valueOf(System.currentTimeMillis()).substring(0, 5) + "appbyme_key";
        return StringUtil.stringToMD5(s).substring(8, 16);
    }

    public static Drawable getMaterialBanner(Context context) {
        TypedArray typedArray = context.getResources().obtainTypedArray(R.array.material_banners);
        Calendar calendar = Calendar.getInstance();
        int index = calendar.get(Calendar.DAY_OF_WEEK) % typedArray.length();
        Drawable drawable = typedArray.getDrawable(index);
        typedArray.recycle();
        return drawable;
    }

    public static String getReplyDetailHtmlHeader(Context context) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(context.getResources().openRawResource(R.raw.reply_detail)));
        StringBuilder stringBuilder = new StringBuilder();
        String temp;
        try {
            while ((temp = reader.readLine()) != null) {
                stringBuilder.append(temp);
            }
        } catch (IOException ignored) {

        } finally {
            try {
                reader.close();
            } catch (IOException ignored2) {
            }
        }
        return stringBuilder.toString();
    }

    public static String getCacheSize(Context context) {
        return StringUtil.formatFileSize(FileUtil.getFileSize(context.getCacheDir()));
    }

    public static String getPicturesPath(Context context) {
        return context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) + "/";
    }

    public static boolean createShortCut(Context context) {
        if (isShortCutExisted(context)) {
            return true;
        }
        Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, context.getString(R.string.app_name));
        shortcut.putExtra("duplicate", false);//设置是否重复创建
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setClass(context, WelcomeActivity.class);//设置第一个页面
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
        Intent.ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(context, R.mipmap.ic_launcher);
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
        context.sendBroadcast(shortcut);
        return true;
    }

    public static boolean isShortCutExisted(Context context) {
        boolean isInstallShortcut = false;
        ContentResolver cr = context.getContentResolver();
        String AUTHORITY = getAuthorityFromPermission(context, "com.android.launcher.permission.READ_SETTINGS");
        Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/favorites?notify=true");
        Cursor c = cr.query(CONTENT_URI, new String[]{"title", "iconResource"}, "title=?", new String[]{context.getString(R.string.app_name)}, null);
        if (c != null && c.getCount() > 0) {
            isInstallShortcut = true;
            System.out.println("已经存在快捷方式");
        }
        return isInstallShortcut;
    }

    public static String getAuthorityFromPermission(Context context, String permission){
        if (permission == null) return null;
        List<PackageInfo> packs = context.getPackageManager().getInstalledPackages(PackageManager.GET_PROVIDERS);
        if (packs != null) {
            for (PackageInfo pack : packs) {
                ProviderInfo[] providers = pack.providers;
                if (providers != null) {
                    for (ProviderInfo provider : providers) {
                        if (permission.equals(provider.readPermission)) return provider.authority;
                        if (permission.equals(provider.writePermission)) return provider.authority;
                    }
                }
            }
        }

        return null;
    }

}
